package com.yk.filedownload.downloader.linstener;


import com.yk.filedownload.ConfigIt.Configuration;
import com.yk.filedownload.DataTransfer.RedisOp.RedisOperation;
import com.yk.filedownload.downloader.DownloadCell.CommonCell;
import com.yk.filedownload.threadpool.DownloadThreadPool;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Project Name:cykfiledownload
 * File Name:ThreadListener
 * Package Name:com.yk.filedownload.downloader.linstener
 * Date:2017\12\11 0011
 * Author:dengtianjia
 * Description:
 * Copyright (c) 2017, 重庆云凯科技有限公司 All Rights Reserved.
 */
public class ThreadListener implements Runnable {

    /**
     * 实时下载速率
     */
    public double RealTimeDownRate;
    /**
     * 实时下载文件数
     */
    public int RealTimeFileNum;
    /**
     * 实时运行的线程数
     */
    public int ThreadNum;


    private RedisOperation redisOperation ;
    private DownloadThreadPool downloadThreadPool;
    /**
     * 下载低速list
     */
    public static List<String> LOWRATE_DOWNLOAD_URLS;

    public ThreadListener(RedisOperation redisOperation , DownloadThreadPool downloadThreadPool) {
        LOWRATE_DOWNLOAD_URLS = new ArrayList<>();
        this.downloadThreadPool = downloadThreadPool;
        this.redisOperation = redisOperation;

    }

    @Override
    public void run() {
            System.out.println("进入线程监控run方法");
            Thread.currentThread().setPriority(6);
            Map<Object, String> StatFileNum = new HashMap<>();
            synchronized (downloadThreadPool) {
                System.out.println("进入同步代码块");
                for (CommonCell cell : downloadThreadPool.getWorkQueue()) {
                    Map status = cell.getSatus();
                    Double realtime_rate = (Double) status.get("Thread_Rate");
                    System.out.println(realtime_rate);
                    if (!StatFileNum.containsKey(status.get("Thread_URL"))) {
                        StatFileNum.put(status.get("Thread_URL"), "");
                    }
                    RealTimeDownRate += realtime_rate;
                }
                RealTimeFileNum = StatFileNum.size();
                ThreadNum = downloadThreadPool.getActiveCount();
                JSONObject json = new JSONObject();
                json.put("RealTimeDownRate",RealTimeDownRate+"KB/S ");
                json.put("RealTimeFileNum",RealTimeFileNum);
                json.put("ThreadNum",ThreadNum);
                /**
                 * 测试代码
                 */
                System.out.println(json.toString());
                /**
                 * 监控状态写入redis
                 */
//                redisOperation.add(Configuration.STATUS_MONITORING_OF_FILEDOWN_KEY_IN_REDIS, this.getRealTimeStatusJson());
                /**
                 * 重新初始化监控状态
                 */
                this.RealTimeDownRate = 0;
                StatFileNum.clear();
        }
    }


}
